<?php


namespace EchoPHP\Database\Transaction;

use Throwable;
use Exception;
use Closure;

trait ManageTransactions {

    /**
     * 事务执行
     * @param Closure $callback
     * @return mixed
     * @throws Throwable
     */
    public function transaction(Closure $callback) {
        $this->beginTransaction();

        try {
            return tap($callback($this), function () {
                $this->commit();
            });
        } catch (Exception $e) {
            $this->rollback();
            throw $e;
        } catch (Throwable $e) {
            $this->rollback();
            throw $e;
        }
    }

    /**
     * 开启事务
     */
    public function beginTransaction() {
        $this->getConnector()->beginTransaction();
    }

    /**
     * 事务提交
     */
    public function commit() {
        $this->getConnector()->commit();
    }

    /**
     * 事务回滚
     */
    public function rollback() {
        $this->getConnector()->rollBack();
    }

}